﻿/****************************************************************************
*                                                                           *
* Copyright (c) Ionescu M. Marius. All rights reserved(2010).               *
*                                                                           *
****************************************************************************/

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Web.UI.DataVisualization.Charting;
using NS_Controls;

public partial class Preview : SessionPageBase
{
	protected void Page_Load(object sender, EventArgs e)
    {
		try
		{
			if (!IsPostBack)
			{
				CommonSession.StareDiagramaIndicatori info = null;
				DataTable data = CommonSession.GetContents(this, Request.QueryString["info"], out info);
				AddPercentageColumn(ref data); //BEFORE filtering...
				areaTitle.InnerText = info.sPageTitle;
				chartPreview.Titles[0].Text = info.sChartTitle;
				if (info.nItemsPerPage < 1)
					grPreview.PageSize = data.Rows.Count;
				else
				{
					grPreview.PageSize = info.nItemsPerPage;
					//extraInfo.Text = string.Format("Pagina {0} din {1} ({2} linii in total), {3} linii pe pagina.",
					//    info.nCurrentPage, grPreview.PageCount, data.Rows.Count, info.nItemsPerPage);
				}
				grPreview.PageIndex = info.nCurrentPage;
				DataView filteredView = data.DefaultView; //or: new DataView(data);
				if (!string.IsNullOrEmpty(info.rowFilter))
				{
					filteredView.RowFilter = info.rowFilter;
					extraInfo.Text = "(Date filtrate)";
				}
				if (!string.IsNullOrEmpty(info.sortExpression))
					grPreview.Sort(info.sortExpression, info.sortDirection.ToUpper()[0] == 'A' ? SortDirection.Ascending : SortDirection.Descending);
				#region Prepare Columns:
				int colIndex = 0;
				foreach (string colName in info.columnIds)
				{
					BoundField bf = new BoundField();
					bf.DataField = colName;
					bf.HeaderText = info.columnNames[colIndex++];
					bf.SortExpression = colName;
					bf.ReadOnly = true;
					grPreview.Columns.Add(bf);
				}
				#endregion
				grPreview.DataSource = filteredView.ToTable().DefaultView;
				grPreview.DataBind();
				BuildChart(chartPreview, grPreview, info.sChartType);
			}
		}
		catch (Exception ex)
		{
			this.SetMessage(ex.Message, true);
			output.Text = ex.ToString();
		}
    }

	private void AddPercentageColumn(ref DataTable data)
	{
		data.Columns.Add("Percentage");
		decimal sum = 0;
		foreach (DataRow dr in data.Rows)
			sum += System.Convert.ToDecimal(dr["NrExtern"]);
		foreach (DataRow dr in data.Rows)
		{
			decimal currentValue = System.Convert.ToDecimal(dr["NrExtern"]);
			dr["Percentage"] = (currentValue == 0 ? 0 : System.Convert.ToInt32(100 * currentValue / sum));
		}
	}

    private void BuildChart(System.Web.UI.DataVisualization.Charting.Chart target, ExtendedGridView data, string chartType)
    {
		if (data.DataSource == null)
		{
			throw new ApplicationException("No data!");
		}
		target.Series.Clear();

        target.Series.Add("Procentaj");
        if (!string.IsNullOrEmpty(chartType))
            target.Series[0].ChartType = GetChartType(chartType);


        int pgOffset = data.PageSize * data.PageIndex;
		while ((data.DataSource.Count <= pgOffset) && (pgOffset > 0))
			pgOffset -= data.PageSize;

        decimal runningTotal = 0;
        for (int i = 0; i < data.PageSize; ++i)
			if ((i + pgOffset) < data.DataSource.Count)
            {
                DataRowView dr = data.DataSource[i + pgOffset];
				decimal currentValue = System.Convert.ToDecimal(dr["NrExtern"]);
                runningTotal += currentValue;
				target.Series[0].Points.AddXY(dr["Percentage"].ToString() + "%", dr["NrExtern"]);
				target.Series[0].Points[target.Series[0].Points.Count - 1].LegendText = dr["ID"].ToString();
            }
		//target.Series[0].Points.AddXY(System.Convert.ToInt32(100 * (sum - runningTotal) / sum).ToString() + "%", sum - runningTotal);
		//target.Series[0].Points[target.Series[0].Points.Count - 1].LegendText = "other";
	}

    private System.Web.UI.DataVisualization.Charting.SeriesChartType GetChartType(string chartType)
    {
        return (System.Web.UI.DataVisualization.Charting.SeriesChartType)Enum.Parse(typeof(System.Web.UI.DataVisualization.Charting.SeriesChartType), chartType);
    }
}
